package com.njupt.backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/15 14:08
 * @Description: 131. 分割回文串
 * @Version: 1.0
 */


public class Partition_131 {

    public List<List<String>> partition(String s) {
        List<List<String>> results = new ArrayList<>();
        List<String> result = new LinkedList<>();
        int startIndex = 0;
        traceBacking(startIndex,s,results,result);


        return results;

    }

    private void traceBacking(int startIndex, String s, List<List<String>> results, List<String> result) {

       if(startIndex == s.length()){
           results.add(new LinkedList(result));
           return ;
       }

        for (int i = startIndex; i < s.length(); i++) {
            if(isPalindrome(s,startIndex,i)){
                result.add(s.substring(startIndex, i + 1));
            }else {
                continue;
            }
            traceBacking(i+1,s,results,result);
            result.remove(result.size()-1);
        }

    }

    public boolean isPalindrome(String s,int start,int end){

        while(true){
            if(s.charAt(start) != s.charAt(end)){
                return false;
            }
            start++;
            end--;
            if(start>end){
                break;
            }
        }
        return true;
    }


    public static void main(String[] args) {
        Partition_131 test = new Partition_131();
        String s = "aab";
        List<List<String>> results = test.partition(s);
        System.out.println(results);

    }
}
